To add a SearchBox, use these components:

SearchBoxConnector(
    searcher
    viewModel
    searchMode
    debouncer
)

Components

searcher
Searcher
required

The Searcher that handles your searches.

viewModel
SearchBoxViewModel
default:"SearchBoxViewModel()"

The business logic that handles new search inputs.

searchMode
SearchMode
default:"SearchMode.AsYouType"
  • SearchMode.AsYouType triggers a search on each keystroke.
  • SearchMode.OnSubmit trigger a search on submitting the query.
debouncer
Debouncer
default:"Debouncer(debounceLoadingInMillis)"

Delays searcher operations by a specified time.

Views

searchBoxView
SearchBoxView
required

The view that handles the input.

val searchView = SearchView(this)
val view: SearchBoxView = SearchBoxViewAppCompat(searchView)
searchBox.connectView(view)

Compose UI

InstantSearch provides SearchBoxState as a state model, which is an implementation of the SearchBoxView interface. You need to connect SearchBoxState to the SearchBoxConnector or SearchBoxViewModel like any other SearchBoxView implementation, and create a Compose UI view that handles the query input, you can directly use the SearchBoxState as a state model. It provides the query property along with the setText function to streamline the design process of your custom Compose UI view.

class MyActivity : AppCompatActivity() {
    val searcher = HitsSearcher(
        applicationID = ApplicationID("NIN726RTTK"),
        apiKey = APIKey("02ad64b3d0a1f6ea65ecbddf6aa250f2"),
        indexName = IndexName("YourIndexName")
    )
    val searchBoxState = SearchBoxState()
    val searchBox = SearchBoxConnector(searcher)
    val connections = ConnectionHandler(searchBox)

    init {
        connections += searchBox.connectView(searchBoxState)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            TextField(
                // set query as text value
                value = searchBoxState.query,
                // update text on value change
                onValueChange = { searchBoxState.setText(it) },
                // set ime action to "search"
                keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
                // set text as query submit on search action
                keyboardActions = KeyboardActions(
                    onSearch = { searchBoxState.setText(searchBoxState.query, true)}
                )
            )
        }
        searcher.searchAsync()
    }

    override fun onDestroy() {
        super.onDestroy()
        connections.disconnect()
        searcher.cancel()
    }
}

See also